#include <stdio.h>
#include "pico8_font3x5.xpm"

const int font_width  = 8;
const int font_height = 8;
const int char_per_line = 16;

char digit_to_hex(int x) {
   if(x < 10) {
      return ('0' + x);
   } else {
      return ('a' + (x - 10));
   }
}

char digit_to_HEX(int x) {
   if(x < 10) {
      return ('0' + x);
   } else {
      return ('A' + (x - 10));
   }
}

char* int_to_hex(int x) {
   static char buf[3] = {0,0,0};
   buf[0] = digit_to_hex(x >> 4);
   buf[1] = digit_to_hex(x & 15);
   return buf;
}

void printb(int x) {
   for(int b=0; b<8; ++b) {
      printf("%c", (x & (1<<b)) ? '*' : ' ');
   }
}


int get_font_column(int c, int column) {
   int result = 0;
   int char_line   = c / char_per_line;
   int char_column = c % char_per_line;
   for(int i=0; i<8; ++i) {
      int xpm_line   = 19 + (char_line * font_height) + i;
      int xpm_column = (char_column * font_width) + column;
      if(pico8_font3x5_xpm[xpm_line][xpm_column] != ' ') {
	  result = result | (1 << i);
      }
   }
//   printb(result);
//   printf("\n"); 
   return result;
}


unsigned int font_data[255];

void print_char(char c) {
    unsigned int chardata = font_data[c - ' '];
    for(int row=0; row<5; ++row) {
	for(int col=0; col<3; ++col) {
	    unsigned int coldata = (chardata >> (5 * col)) & 31 ;
	    unsigned int BW = coldata & (1 << row);
	    printf("%c",BW?'*':' ');
	}
	printf("\n");
    }
    printf("\n");
}

void print_string(const char* s) {
    for(const char* p=s; *p; ++p) {
	print_char(*p);
    }
}

int main() {

    printf("# Generated by FIRMWARE/TOOLS/FONT/makefont.c\n");
    printf(".globl font_3x5\n");
    printf(".LC0:\n");
    for(int car=0; car < 16*6; ++car) {
      unsigned int col1 = get_font_column(car, 0);
      unsigned int col2 = get_font_column(car, 1);
      unsigned int col3 = get_font_column(car, 2);

      unsigned int charcode = 
	 col1           |
	(col2    << 5 ) |
	(col3    << 10) ;
      printf(".hword 0x%04lx\n", charcode);
      font_data[car] = charcode;
//    printf("\n");
   }
   printf("font_3x5:\n");
   printf("    .word .LC0\n");	

// print_string("Hello, world !!");
}
